package com.gopay.scheduler.service.cbrmb.impl;

import com.gopay.common.constants.mail.MailLevel;
import com.gopay.common.constants.mail.MailTemplateType;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.domain.cust.CustCorpInfo;
import com.gopay.common.domain.mail.Send;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.user.dao.CustCorpInfoQueryDAO;
import com.gopay.remote.cps.mail.MailRemoteService;
import com.gopay.scheduler.service.cbrmb.CbRmbIntlDishonorAccountingFailService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author b.zou
 * @description
 * @class CbRmbIntlDishonorAccountingFailServiceImpl
 * @date 2018.1.8
 */
@Service("cbRmbIntlDishonorAccountingFailService")
public class CbRmbIntlDishonorAccountingFailServiceImpl implements CbRmbIntlDishonorAccountingFailService {

    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;

    @Resource(name="custCorpInfoQueryDao")
    private CustCorpInfoQueryDAO custCorpInfoQueryDAO;

    private @Value("#{webProperties['portal.url']}") String portalUrl;
    private @Value("#{webProperties['cbrmb.intlcard.riskcontroller.email']}") String riskControlEmail;

    @Resource(name="mailRemoteService")
    private MailRemoteService mailRemoteService;

    @Override
    public List<String> getCustIds(Map<String, Object> params) {
        List<String> custList = new ArrayList<>();
        StringBuilder sql = new StringBuilder();
        sql.append(" select m.mer_id from cps_gen_main_order m ");
        sql.append(" inner join cb_rmb_intlcard_dishonor d on m.gopay_order_id=d.dishonor_order_id and d.fund_status in('02','04') ");
        sql.append(" where m.gopay_int_txn_cd in('01743','01744') ");
        sql.append(" and m.gopay_txn_tm >=to_date(:timeBegin,'yyyy-MM-dd hh24:mi:ss') ");
        sql.append(" and m.gopay_txn_tm <=to_date(:timeEnd,'yyyy-MM-dd hh24:mi:ss') ");
        sql.append(" group by m.mer_id  ");
        List<Object[]> list = commonQueryDAO.findBySql(sql.toString(),params);
        if (list != null && list.size() > 0) {
            for (Object custId : list) {
                custList.add(String.valueOf(custId));
            }
        }
        return custList;
    }

    @Override
    public void sendCustEmail(Map<String, Object> params) {
        String custId = (String)params.get("custId");
        List<String> tran01743Orders = this.getOrdersByCustId(params, IntTxnCd._01743.value);
        List<String> tran01744Orders = this.getOrdersByCustId(params, IntTxnCd._01744.value);
        if(tran01743Orders.size()>0 || tran01744Orders.size()>0){
            CustCorpInfo custInfo = custCorpInfoQueryDAO.getByCustId(custId);
            String tran01743Message = "";
            String tran01744Message = "";
            StringBuilder tran01743Builder;
            StringBuilder tran01744Builder;
            if(tran01743Orders.size()>0){
                tran01743Builder = new StringBuilder();
                tran01743Builder.append("您有"+tran01743Orders.size()+"笔拒付订单,原支付单号为：");
                for (String orderId : tran01743Orders) {
                    tran01743Builder.append(orderId+"；");
                }
                tran01743Builder.append("，仍未扣款（冻结）成功，请及时充值拒付清算金额和手续费！");
                tran01743Message = tran01743Builder.toString();
                tran01743Message = tran01743Message.replace("；，","，");
            }
            if(tran01744Orders.size()>0){
                tran01744Builder = new StringBuilder();
                tran01744Builder.append("您有"+tran01744Orders.size()+"笔调单订单,原支付单号为：");
                for (String orderId : tran01744Orders) {
                    tran01744Builder.append(orderId+"；");
                }
                tran01744Builder.append("，仍未扣款成功，请及时充值调单手续费！");
                tran01744Message = tran01744Builder.toString();
                tran01744Message = tran01744Message.replace("；，","，");
            }
            Send send = new Send();
            send.setReceivers(custInfo.getEmail());
            send.setTemplate(MailTemplateType.INTLCARD_DISHONOR_ACCOUNTING_FAIL_CUST.value);
            send.setLevel(MailLevel.MID);
            Map<String, Object> json = new HashMap<>(4);
            json.put("CUST_NAME", custInfo.getCorpName());
            json.put("MESSAGE1", tran01743Message);
            json.put("MESSAGE2", tran01744Message);
            json.put("replacethistotheLogoAddr", portalUrl);
            send.setContent(JSONObject.fromObject(json).toString());
            //调用邮件服务接口
            mailRemoteService.addMailTask(send);
        }
    }

    @Override
    public String getRiskMsgByCustId(Map<String, Object> params) {
        String custId = (String)params.get("custId");
        List<String> tran01743Orders = this.getOrdersByCustId(params, IntTxnCd._01743.value);
        List<String> tran01744Orders = this.getOrdersByCustId(params, IntTxnCd._01744.value);
        String tran01743Message = "";
        String tran01744Message = "";
        if(tran01743Orders.size()>0 || tran01744Orders.size()>0) {
            CustCorpInfo custInfo = custCorpInfoQueryDAO.getByCustId(custId);
            StringBuilder tran01743Builder;
            StringBuilder tran01744Builder;
            if (tran01743Orders.size() > 0) {
                tran01743Builder = new StringBuilder();
                tran01743Builder.append(custInfo.getCorpName()+"（客户名称），商户邮箱"+ custInfo.getEmail()+ "有" + tran01743Orders.size() + "笔拒付订单,原支付单号为：");
                for (String orderId : tran01743Orders) {
                    tran01743Builder.append(orderId + "；");
                }
                tran01743Builder.append("。\n");
                tran01743Message = tran01743Builder.toString();
                tran01743Message = tran01743Message.replace("；。", "。");
            }
            if (tran01744Orders.size() > 0) {
                tran01744Builder = new StringBuilder();
                tran01744Builder.append(custInfo.getCorpName()+"（客户名称），商户邮箱"+ custInfo.getEmail()+ "有" + tran01744Orders.size() + "笔调单订单,原支付单号为：");
                for (String orderId : tran01744Orders) {
                    tran01744Builder.append(orderId + "；");
                }
                tran01744Builder.append("。\n");
                tran01744Message = tran01744Builder.toString();
                tran01744Message = tran01744Message.replace("；。", "。");
            }
        }
        return tran01743Message+tran01744Message;
    }

    @Override
    public void sendRiskControllerEmail(String message) {
        Send send = new Send();
        send.setReceivers(riskControlEmail);
        send.setTemplate(MailTemplateType.INTLCARD_DISHONOR_ACCOUNTING_FAIL_RISKCONTROLLER.value);
        send.setLevel(MailLevel.MID);
        Map<String, Object> json = new HashMap<>(4);
        json.put("MESSAGE", message);
        json.put("replacethistotheLogoAddr", portalUrl);
        send.setContent(JSONObject.fromObject(json).toString());
        //调用邮件服务接口
        mailRemoteService.addMailTask(send);
    }

    private List<String> getOrdersByCustId(Map<String, Object> params, String tranType) {
        List<String> orderList = new ArrayList<>();
        StringBuilder sql = new StringBuilder();
        params.put("tranType",tranType);
        sql.append(" select m.relevance_gopay_order_id from cps_gen_main_order m ");
        /* 01,03测试用 */
        /*sql.append(" inner join cb_rmb_intlcard_dishonor d on m.gopay_order_id=d.dishonor_order_id and d.fund_status in('01','03') ");*/
        sql.append(" inner join cb_rmb_intlcard_dishonor d on m.gopay_order_id=d.dishonor_order_id and d.fund_status in('02','04') ");
        sql.append(" where m.gopay_int_txn_cd =:tranType ");
        sql.append(" and m.mer_id =:custId ");
        sql.append(" and m.gopay_txn_tm >=to_date(:timeBegin,'yyyy-MM-dd hh24:mi:ss') ");
        sql.append(" and m.gopay_txn_tm <=to_date(:timeEnd,'yyyy-MM-dd hh24:mi:ss') ");
        List<Object[]> list = commonQueryDAO.findBySql(sql.toString(),params);
        if (list != null && list.size() > 0) {
            for (Object orderId : list) {
                orderList.add(String.valueOf(orderId));
            }
        }
        return orderList;
    }
}
